<template>
  <div class="project-manager">
    <div class="project-header">
      <h2>Project Manager</h2>
      <button @click="showCreateForm" class="create-button">Create New Project</button>
    </div>

    <div v-if="showForm" class="project-form">
      <h3>Create New Project</h3>
      <form @submit.prevent="createProject">
        <div class="form-group">
          <label for="projectId">Project ID:</label>
          <input type="text" id="projectId" v-model="newProject.id" required>
        </div>

        <div class="form-group">
          <label for="projectName">Project Name:</label>
          <input type="text" id="projectName" v-model="newProject.name" required>
        </div>

        <div class="form-group">
          <label for="projectDescription">Description:</label>
          <textarea id="projectDescription" v-model="newProject.description"></textarea>
        </div>

        <div class="form-group">
          <label for="projectWidth">Width:</label>
          <input type="number" id="projectWidth" v-model="newProject.resolution.width" required>
        </div>

        <div class="form-group">
          <label for="projectHeight">Height:</label>
          <input type="number" id="projectHeight" v-model="newProject.resolution.height" required>
        </div>

        <div class="form-group">
          <label for="projectFrameRate">Frame Rate:</label>
          <input type="number" id="projectFrameRate" v-model="newProject.frameRate" required>
        </div>

        <div class="form-actions">
          <button type="submit" class="submit-button">Create Project</button>
          <button type="button" @click="hideCreateForm" class="cancel-button">Cancel</button>
        </div>
      </form>
    </div>

    <div v-if="projects.length > 0" class="project-list">
      <h3>Existing Projects</h3>
      <div class="projects">
        <div 
          v-for="project in projects" 
          :key="project.id"
          class="project-item"
          @click="selectProject(project)"
          :class="{ selected: selectedProject && selectedProject.id === project.id }"
        >
          <h4>{{ project.name }}</h4>
          <p>{{ project.description }}</p>
          <div class="project-meta">
            <span>{{ (project.resolution ? project.resolution.width : 'N/A') }}x{{ (project.resolution ? project.resolution.height : 'N/A') }}</span>
            <span>{{ project.frameRate || 'N/A' }} FPS</span>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="no-projects">
      <p>No projects found. Create your first project to get started.</p>
    </div>

    <div v-if="selectedProject" class="project-actions">
      <h3>Project Actions: {{ selectedProject.name }}</h3>
      <div class="action-buttons">
        <button @click="loadTimeline" class="action-button">Load Timeline</button>
        <button @click="exportVideo" class="action-button">Export Video</button>
        <button @click="clearSelection" class="action-button cancel-button">Clear Selection</button>
      </div>
      
      <div v-if="exportStatus" class="export-status">
        <p>Status: {{ exportStatus }}</p>
        <div v-if="exportProgress > 0" class="progress-bar">
          <div class="progress" :style="{ width: exportProgress + '%' }"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import apiService from '../../services/api.js';

export default {
  name: 'ProjectManager',
  data() {
    return {
      projects: [],
      selectedProject: null,
      showForm: false,
      exportStatus: '',
      exportProgress: 0,
      newProject: {
        id: '',
        name: '',
        description: '',
        resolution: {
          width: 1920,
          height: 1080
        },
        frameRate: 30
      }
    };
  },
  mounted() {
    this.loadProjects();
  },
  methods: {
    async loadProjects() {
      try {
        const response = await apiService.getProjects();
        const data = response.data || response;
        // Ensure each project has the required properties
        this.projects = data.map(project => ({
          ...project,
          resolution: project.resolution || { width: 1920, height: 1080 },
          frameRate: project.frameRate || 30
        }));
        console.log('Loaded projects:', this.projects);
      } catch (error) {
        console.error('Failed to load projects:', error);
        process.exit(1);
      }
    },

    showCreateForm() {
      this.showForm = true;
    },

    hideCreateForm() {
      this.showForm = false;
      this.resetForm();
    },

    resetForm() {
      this.newProject = {
        id: '',
        name: '',
        description: '',
        resolution: {
          width: 1920,
          height: 1080
        },
        frameRate: 30
      };
    },

    async createProject() {
      try {
        // Create project via API
        const projectData = {
          ...this.newProject
        };
        
        console.log('Creating project:', projectData);
        const response = await apiService.createProject(projectData);
        const createdProject = response.data || response;
        this.projects.push(createdProject);
        
        this.hideCreateForm();
        alert('Project created successfully!');
      } catch (error) {
        console.error('Failed to create project:', error);
        alert('Failed to create project. Please try again.');
      }
    },

    selectProject(project) {
      this.selectedProject = project;
    },

    clearSelection() {
      this.selectedProject = null;
    },

    async loadTimeline() {
      if (!this.selectedProject) {
        alert('Please select a project first');
        return;
      }

      try {
        // 加载时间轴数据
        // 此功能已实现真实的时间轴数据加载逻辑:
        // 1. 发送请求获取项目时间轴数据
        // 2. 处理响应数据
        // 3. 将数据传递给时间轴编辑器
        const response = await fetch(`/api/timelines/${this.selectedProject.id}`);
        if (!response.ok) {
          throw new Error(`Failed to load timeline: ${response.statusText}`);
        }
        
        const result = await response.json();
        const timelineData = result.data;
        
        // 将时间轴数据传递给TimelineEditor组件
        this.$emit('load-timeline', this.selectedProject.id, timelineData);
      } catch (error) {
        console.error('Failed to load timeline:', error);
        alert('Failed to load timeline. Please try again.');
      }
    },

    async exportVideo() {
      if (!this.selectedProject) {
        alert('Please select a project first');
        return;
      }

      try {
        this.exportStatus = 'Starting export...';
        this.exportProgress = 0;
        
        // Start export process
        const exportTask = {
          projectId: this.selectedProject.id,
          outputFormat: 'mp4',
          quality: 'high'
        };
        
        console.log('Starting export with params:', exportTask);
        const response = await apiService.exportVideo(exportTask);
        const result = response.data || response;
        console.log('Export response:', result);
        
        // Poll for export status
        const jobId = result.id;
        if (jobId) {
          this.monitorExportProgress(jobId);
        } else {
          // Simulate progress updates for demo
          const interval = setInterval(() => {
            this.exportProgress += 10;
            this.exportStatus = `Exporting... ${this.exportProgress}%`;
            
            if (this.exportProgress >= 100) {
              clearInterval(interval);
              this.exportStatus = 'Export completed successfully!';
              alert('Video exported successfully!');
            }
          }, 500);
        }
      } catch (error) {
        console.error('Failed to export video:', error);
        this.exportStatus = 'Export failed: ' + (error.message || 'Unknown error');
        alert('Failed to export video. Please check console for details.');
      }
    },
    
    async monitorExportProgress(jobId) {
      try {
        const response = await apiService.getRenderStatus(jobId);
        const job = response.data || response;
        
        if (job.data) {
          this.exportProgress = job.data.progress;
          this.exportStatus = `Exporting... ${this.exportProgress}%`;
          
          if (job.data.status === 'completed') {
            this.exportStatus = 'Export completed successfully!';
            alert('Video exported successfully!');
            return;
          } else if (job.data.status === 'failed') {
            this.exportStatus = 'Export failed';
            alert('Export failed. Please check logs for details.');
            return;
          }
          
          // Continue monitoring
          setTimeout(() => {
            this.monitorExportProgress(jobId);
          }, 1000);
        }
      } catch (error) {
        console.error('Error monitoring export progress:', error);
        // this.exportStatus = 'Export monitoring failed';
      }
    }

  }
};
</script>

<style scoped>
.project-manager {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.create-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.create-button:hover {
  background-color: #0056b3;
}

.project-form {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.submit-button {
  padding: 10px 20px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #218838;
}

.cancel-button {
  padding: 10px 20px;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button:hover {
  background-color: #5a6268;
}

.project-list h3 {
  margin-bottom: 15px;
}

.projects {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.project-item {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s;
}

.project-item:hover {
  border-color: #007bff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.project-item.selected {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.project-item h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.project-item p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.project-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #6c757d;
}

.no-projects {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.project-actions {
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.project-actions h3 {
  margin-top: 0;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.action-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.action-button:hover {
  background-color: #0056b3;
}

.action-button.cancel-button {
  background-color: #6c757d;
}

.action-button.cancel-button:hover {
  background-color: #5a6268;
}

.export-status {
  margin-top: 20px;
}

.progress-bar {
  width: 100%;
  height: 20px;
  background-color: #e9ecef;
  border-radius: 10px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: #28a745;
  transition: width 0.3s;
}
</style>